package com.future.controller;

import java.util.List;

import javax.validation.constraints.NotNull;

import com.future.common.annotation.ControllerMapping;
import com.future.common.base.BaseController;
import com.future.common.exception.AppException;
import com.future.dao.BjDao;
import com.future.requestbean.Bj;
import com.future.requestbean.BjUpdate;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.tx.Tx;

@ControllerMapping("/bj")
public class BjController extends BaseController {
	@Inject
	private BjDao bjDao;

	public void getBj() {
		renderResult("bj", this.bjDao.findAll());
	}

	@Before(Tx.class)
	public void addBj() {
		Bj bj = getJsonBody(Bj.class);
		List<com.future.model.Bj> bjList = this.bjDao.getBjByBjName(bj.getClassname());
		if (bjList.size() > 0) {
			throw new AppException("已经存在该名字的班级");
		}
		com.future.model.Bj bjM = beanToModel(bj, com.future.model.Bj.class);
		this.bjDao.save(bjM);
		renderSuccess();

	}

	@Before(Tx.class)
	public void deleteBj(@NotNull(message = "选择删除的班级") Long bjid) {
		this.bjDao.deleteById(bjid);
		renderSuccess();
	}

	@Before(Tx.class)
	public void bjUpdate() {
		com.future.model.Bj bj = getJsonBodyToModel(BjUpdate.class, com.future.model.Bj.class);
		List<com.future.model.Bj> bjList = this.bjDao.getBjByBjName(bj.getClassname());
		if (bjList.size() > 0 && bjList.get(0).getClassid() != bj.getClassid()) {
			throw new AppException("已经存在该名字的班级");
		}
		this.bjDao.update(bj);
		renderSuccess();
	}
}
